import fetch from 'isomorphic-fetch'

export const INCREMENT_COUNTER = 'INCREMENT_COUNTER'
export const DECREMENT_COUNTER = 'DECREMENT_COUNTER'
export const FETCH_COUNTER = 'FETCH_COUNTER'

export function gotoReg() {
  window.location.href = '#/reg';
}

export function increment() {
  return {
    type: INCREMENT_COUNTER
  }
}

export function decrement() {
  return {
    type: DECREMENT_COUNTER
  }
}

export function fetchAdd(num) {
  return {
     type: FETCH_COUNTER,
     num: num
  }
}

export function incrementIfOdd() {
  return (dispatch, getState) => {
    const { counter } = getState()

    if (counter % 2 === 0) {
      return
    }

    dispatch(increment())
  }
}

export function incrementAsync(delay = 1000) {
  return dispatch => {
    setTimeout(() => {
      dispatch(increment())
    }, delay)
  }
}

export function fetchAsync() {
  return (dispatch, getState) => {
     return fetch('http://www.peas_leaf.com/api.php')
      .then(response => response.json())
      .then(data => dispatch(fetchAdd(data))) 
      .catch(function(e) {
         console.log("Oops, error");
      })
  }
}

